import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/layout'
import Login from '@/views/Login'

Vue.use(VueRouter)

// 路由配置
const routes = [
  // 后台主页面
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      // 首页
      {
        path: '/home',
        name: 'home',
        meta: { title: '数据' },
        component: () => import(/* webpackChunkName: "home" */ '../views/Home')
      }
    ]
  },
  // 登录区域
  {
    path: '/login',
    name: 'login',
    meta: { title: '登录' },
    component: Login
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (token) {
    document.title = to.meta.title
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
